package com.geek.service.impl;


import com.github.pagehelper.PageHelper;
import com.geek.bean.data.CouponExchangeData;
import com.geek.mapper.MarketCouponMapper;
import com.geek.model.MarketCoupon;
import com.geek.model.MarketCouponExample;

import com.geek.mapper.MarketCouponMapper;
import com.geek.mapper.MarketCouponUserMapper;
import com.geek.model.*;

import com.geek.service.CouponService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service
public class CouponServiceImpl implements CouponService {
    @Autowired
    MarketCouponMapper couponMapper;
    @Autowired
    MarketCouponUserMapper couponUserMapper;
    @Override
    public List<Map> couponList(Integer userId,int page, int limit) {
        //根据userId查询用户拥有的couponId
        MarketCouponUserExample couponUserExample = new MarketCouponUserExample();
        couponUserExample.createCriteria().andDeletedEqualTo(false);
        List<MarketCouponUser> marketCouponUsers = couponUserMapper.selectByExample(couponUserExample);
        List<Integer> couponIds = marketCouponUsers.stream().map(marketCouponUser -> marketCouponUser.getCouponId()).collect(Collectors.toList());
        //根据couponIds查询用户未拥有的优惠卷
        //当前时间
        Date curren = new Date();
        MarketCouponExample couponExample = new MarketCouponExample();
        //查询普通优惠卷
        couponExample.createCriteria().andDeletedEqualTo(false)
                .andTimeTypeEqualTo((short) 0)
                        .andIdNotIn(couponIds);
        //查询特殊优惠卷
        couponExample.or().andDeletedEqualTo(false)
                .andTimeTypeEqualTo((short) 1)
                .andStartTimeLessThan(curren)//开始小于等于当前时间
                .andEndTimeGreaterThan(curren)//结束大于等于当前时间
                .andIdNotIn(couponIds);
        couponExample.setOrderByClause("add_time desc");
        PageHelper.startPage(page,limit);
        List<MarketCoupon> marketCoupons = couponMapper.selectByExample(couponExample);

        List<Map> couponList = marketCoupons.stream().map(marketCoupon -> {
            Map<String, Object> map = new HashMap<>();
            map.put("id", marketCoupon.getId());
            map.put("name", marketCoupon.getName());
            map.put("desc", marketCoupon.getDesc());
            map.put("tag", marketCoupon.getTag());
            map.put("total", marketCoupon.getTotal());
            map.put("discount", marketCoupon.getDiscount());
            map.put("days", marketCoupon.getDays());
            if (marketCoupon.getTimeType() == 1) {
                map.put("startTime", marketCoupon.getStartTime());
                map.put("endTime", marketCoupon.getEndTime());
            }
            map.put("min", marketCoupon.getMin());
            return map;
        }).collect(Collectors.toList());
        return couponList;
    }

    @Override
    public CouponExchangeData exchange(String code) {
        MarketCouponExample couponExample = new MarketCouponExample();
        couponExample.createCriteria().andDeletedEqualTo(false);
        List<MarketCoupon> couponList = couponMapper.selectByExample(couponExample);
        CouponExchangeData couponExchangeData = new CouponExchangeData();
        for (MarketCoupon marketCoupon : couponList) {
            if (code.equals(marketCoupon.getCode())){
                couponExchangeData.setExchange(true);
                couponExchangeData.setCouponId(marketCoupon.getId());
            }
        }
        return couponExchangeData;
    }

    @Override
    public MarketCoupon selectById(Integer id) {

        return couponMapper.selectByPrimaryKey(id);

    }
    @Override
    public int getAvailableCouponLength(Integer userId) {
        // 获取用户的可用优惠券
        MarketCouponUserExample couponUserExample = new MarketCouponUserExample();
        couponUserExample.createCriteria()
                .andUserIdEqualTo(userId)
                .andStatusEqualTo((short) 0)
                .andDeletedEqualTo(false);
        List<MarketCouponUser> couponUserList = couponUserMapper.selectByExample(couponUserExample);


        // 可用优惠券数量
        int availableCouponLength = 0;
        // 遍历couponUserList，获取可用优惠券数量
        for (MarketCouponUser couponUser : couponUserList) {
            Integer couponId = couponUser.getCouponId();
            MarketCouponExample couponExample = new MarketCouponExample();
            couponExample.createCriteria()
                    .andIdEqualTo(couponId)
                    .andDeletedEqualTo(false)
                    .andStatusEqualTo((short) 0);
            MarketCoupon coupon = couponMapper.selectByExample(couponExample).get(0);
            availableCouponLength += coupon.getLimit();
        }
        return availableCouponLength;
    }

    @Override
    public MarketCoupon findById(Integer couponId) {
        MarketCouponExample example = new MarketCouponExample();
        example.createCriteria()
                .andDeletedEqualTo(false)
                .andIdEqualTo(couponId)
                .andStatusEqualTo((short) 0);
        List<MarketCoupon> coupons = couponMapper.selectByExample(example);
        return coupons != null && coupons.size() > 0 ? coupons.get(0) : null;
    }


    @Override
    public List<MarketCoupon> list(int page, int limit) {
        MarketCouponExample example = new MarketCouponExample();
        example.createCriteria().andDeletedEqualTo(false);
        return couponMapper.selectByExample(example);
    }
    @Override
    public Integer countById(Integer userId) {
        MarketCouponUserExample example = new MarketCouponUserExample();
        example.createCriteria().andDeletedEqualTo(false)
                .andUserIdEqualTo(userId);

        long count = couponUserMapper.countByExample(example);
        return (int)count;


    }

    @Override
    public Boolean isPossess(int userId, Integer couponId) {
        MarketCouponUserExample example = new MarketCouponUserExample();
        example.createCriteria().andDeletedEqualTo(false)
                .andCouponIdEqualTo(couponId)
                .andUserIdEqualTo(userId);

        List<MarketCouponUser> marketCouponUsers = couponUserMapper.selectByExample(example);
        if (marketCouponUsers == null && marketCouponUsers.size() != 1){
            return false;
        }
        return true;
    }
    @Override
    public MarketCoupon findsById(Integer couponId, BigDecimal sum) {
        Date date = new Date();
        MarketCouponExample example = new MarketCouponExample();
        example.createCriteria().andDeletedEqualTo(false)
                .andIdEqualTo(couponId);
//                .andStartTimeGreaterThanOrEqualTo(date)
//                .andEndTimeLessThanOrEqualTo(date);
        List<MarketCoupon> marketCoupons = couponMapper.selectByExample(example);

        if (sum.compareTo(sum.subtract(marketCoupons.get(0).getDiscount())) < 0){
            return null;
        }
        return marketCoupons != null ? marketCoupons.get(0) : null;
    }

}
